package com.http;


import com.orhanobut.logger.Logger;
import com.woke.method.MyApp;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * <p>
 * 标题 ：
 * 备注： 保存Cookie
 */
public class CookiesReceivedInterceptor implements Interceptor {
	@Override
	public Response intercept(Chain chai) throws IOException {
		Request request = chai.request ();
		//请求的url
		Logger.i (String.format ("Request %n %s ", request.url ()));
		if (request.body () instanceof FormBody) {
			FormBody body = (FormBody) request.body ();
			Map<String, String> params = new HashMap<> ();
			for (int i = 0; i < body.size (); i++) {
				params.put (body.encodedName (i), body.encodedValue (i));
			}
			//请求参数
			Logger.i ("Request params \n" + (params == null ? null : params.toString ()));
		}
		//Cookie 缓存到本地
		Response originalResponse = chai.proceed (request);
		if (! originalResponse.headers ("Set-Cookie").isEmpty ()) {
			HashSet<String> cookies = new HashSet<> ();
			for (String header : originalResponse.headers ("Set-Cookie")) {
				cookies.add (header);
			}
			MyApp.newInstance ().saveCookies (cookies);
		}
		//响应的 请求头
		Logger.i ("Cookie 响应 Response :" + originalResponse.headers ().toString ());

		return originalResponse;
	}
}
